<script lang="ts" setup>
import type { DataType } from './types';

import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';

import {
  Button,
  Card,
  message,
  Modal,
  Space,
  Switch,
  Tag,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  getMerchantsList,
  postMerchantsIsDefault,
  postMerchantsNotifyUrl,
  postMerchantsStatus,
} from '#/api/plugin/pay';
import Icon from '#/components/Icons';
import { toggleStatus } from '#/utils';

import { FormModalView } from './components';

defineOptions({
  name: 'PluginWechatAdminIndexwxapp',
});
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
// 去除'管理'和'列表'两个字
const viewTitle = routeMeta.title.replace('管理', '').replace('列表', '');
const statusStr: any = { 0: '未审核', 1: '已审核', 40: '已拉黑', 30: '已驳回' };
const statusColor: any = {
  0: 'default',
  1: 'success',
  40: 'error',
  30: 'warning',
};
const tabKey = ref('wechat');
const tabList = [
  {
    key: 'wechat',
    tab: '微信支付',
  },
  {
    key: 'alipay',
    tab: '支付宝支付',
  },
  {
    key: 'unipay',
    tab: '银联支付',
  },
];
const examineInfo: any = ref();
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入商户名称',
      },
      fieldName: 'keyword',
      label: '商户名称',
    },
    {
      component: 'Select',
      componentProps: {
        options: [
          { label: '未审核', value: 0 },
          { label: '已审核', value: 1 },
          { label: '已拉黑', value: 40 },
          { label: '已驳回', value: 30 },
        ],
        allowClear: true,
      },
      fieldName: 'status',
      label: '状态',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitOnEnter: true,
};
const gridOptions: VxeGridProps<DataType> = {
  rowConfig: {
    isCurrent: true,
    isHover: true,
  },
  columns: [
    { field: 'id', title: '商户编号' },
    { field: 'name', title: '商户名称' },
    {
      field: 'order_total',
      title: '订单总量',
    },
    {
      field: 'total_fee',
      title: '收款总额',
    },
    {
      field: 'status',
      title: '商户状态',
      slots: { default: 'status' },
    },
    {
      field: 'create_time',
      title: '入驻时间',
      formatter: 'formatShortDateTime',
      width: 150,
    },
    {
      field: 'is_default',
      title: '是否默认支付',
      width: 150,
      slots: { default: 'is_default' },
    },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 240,
    },
  ],
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const { data } = await getMerchantsList({
          page: page.currentPage,
          limit: page.pageSize,
          ...formValues,
        });
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});

const onChange = async (row: DataType) => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要${row.is_default === 0 ? '停用' : '启用'}吗?`,
    async onOk() {
      try {
        await postMerchantsIsDefault({ id: row.id });
        message.success(`已${row.is_default === 0 ? '停用' : '启用'}`);
        GridApi.query();
      } catch {
        row.is_default = toggleStatus(row.is_default);
      }
    },
    onCancel() {
      row.is_default = toggleStatus(row.is_default);
    },
  });
};

const [FormModal, formModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: FormModalView,
  onClosed() {
    const formModalData = formModalApi.getData();
    if (formModalData?.isUpdata) {
      GridApi.query();
    }
  },
});

const [ExamineModal, ExamineModalApi] = useVbenModal({
  showCancelButton: false,
  showConfirmButton: false,
});

// 审核操作
async function handleExamine(status: number) {
  const { msg } = await postMerchantsStatus({
    id: examineInfo.value.id,
    status,
  });
  message.success(msg);
  GridApi.query();
  ExamineModalApi.close();
}

// 生成回调地址操作
async function handleNotifyUrl() {
  const currentRecord = GridApi.grid.getCurrentRecord();
  if (!currentRecord) {
    message.error('未选择任何行！');
    return;
  }

  const { msg } = await postMerchantsNotifyUrl({ id: currentRecord.id });

  Modal.confirm({
    title: '系统提示',
    content: h('div', msg),
  });
}

const openDialog = async (
  title: '审核' | '新增' | '编辑',
  row?: DataType | null,
) => {
  if (title === '审核') {
    examineInfo.value = row;
    ExamineModalApi.setState({
      title: `${title}${viewTitle}`,
    });
    ExamineModalApi.open();
  } else {
    formModalApi.setState({
      title: `${title}${viewTitle}`,
    });
    formModalApi.setData(row);
    formModalApi.open();
  }
};
</script>

<template>
  <Page auto-content-height>
    <FormModal />
    <ExamineModal class="w-3/5">
      <Card
        :active-tab-key="tabKey"
        :tab-list="tabList"
        :title="examineInfo.name"
        style="width: 100%"
        @tab-change="(key) => (tabKey = key)"
      >
        <div
          v-for="(info, index) in examineInfo.config[tabKey].default"
          :key="index"
        >
          <p v-if="info">
            <span>{{ index }} </span>
            :<span>{{ info }}</span>
          </p>
        </div>
      </Card>
      <template #append-footer>
        <Space>
          <Button type="primary" @click="handleExamine(1)"> 审核 </Button>
          <Button type="dashed" @click="handleExamine(30)"> 驳回 </Button>
          <Button danger type="primary" @click="handleExamine(40)">
            拉黑
          </Button>
        </Space>
      </template>
    </ExamineModal>
    <Grid :table-title="`${viewTitle}列表`">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="openDialog('新增')">
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          新增{{ viewTitle }}
        </Button>
        <Button class="mr-2" type="primary" @click="handleNotifyUrl()">
          <span class="anticon">
            <Icon icon="ri:links-line" />
          </span>
          生成回调地址
        </Button>
      </template>
      <template #status="{ row }">
        <Tag :color="statusColor[row.status]">{{ statusStr[row.status] }}</Tag>
      </template>
      <template #is_default="{ row }">
        <Switch
          v-model:checked="row.is_default"
          :checked-value="1"
          :un-checked-value="0"
          checked-children="启用"
          un-checked-children="禁用"
          @change="onChange(row)"
        />
      </template>

      <template #action="{ row }">
        <Space>
          <Button class="mr-2" type="primary" @click="openDialog('编辑', row)">
            <span class="anticon">
              <Icon icon="ri:file-edit-line" />
            </span>
            编辑
          </Button>
          <Button type="primary" @click="openDialog('审核', row)">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:send-plane-line" />
              </span>
            </template>
            审核
          </Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
